import { HttpClient } from 'feie-ui'
import { TIMEZONE } from '~/types/enums'

const { VITE_HTTP_TIMEOUT, PROD } = getEnv()

// TODO:这里无法读取$i18n
// const appInst = useNuxtApp()
// const t = appInst.$i18n

const timeZoneList = [
  { label: '世界 UTC+0', value: TIMEZONE.ETC, time_zone: 'utc', offset: 0 },
  { label: '美东时间 UTC-4', value: TIMEZONE.USA, time_zone: 'en_US', offset: 240 },
  { label: '中国 UTC+8', value: TIMEZONE.CST, time_zone: 'zh_CN', offset: -480 },
  { label: '泰国 UTC+7', value: TIMEZONE.THAILAND, time_zone: 'th_TH', offset: -420 },
  { label: '越南 UTC+7', value: TIMEZONE.VIETNAM, time_zone: 'vi_VN', offset: -420 },
  { label: '巴西 UTC-3', value: TIMEZONE.BRT, time_zone: 'pt_BR', offset: 180 },
  { label: '印度 UTC+5:30', value: TIMEZONE.INDIA, time_zone: 'hi_IN', offset: 330 },
  { label: '印度尼西亚 UTC+7', value: TIMEZONE.INDONESIA, time_zone: 'id_ID', offset: -420 },
  { label: '韩国 UTC+9', value: TIMEZONE.KOREA, time_zone: 'ko_KR', offset: -540 },
  { label: '日本 UTC+9', value: TIMEZONE.JAPAN, time_zone: 'ja_JP', offset: -540 },
]

/** 传参需要Cbor加密的接口 */
const cborUrlList = [
  '/member/login',
  '/member/reg',
]

const timeOffset = new Date().getTimezoneOffset()
const timeZone = timeZoneList.filter(tz => tz.offset === timeOffset)[0] ?? timeZoneList[0]

interface IResponse<T> {
  status: boolean
  data: T
  tip?: string
}

function getMsgByCode(data: any) {
  switch (data) {
    case '5023':
    // return t('balance_not_enough')
    default:
      return undefined
  }
}

// token
const dataIsTokenHandler = debounce((responseStatus: any, response: any) => {
  const appStore = useAppStore()
  appStore.removeToken()
  appStore.removeUserInfo()
  appStore.setMqttConnectedFalse()
  socketClient.connect('token失效 重新连接')

  i18nNavigateTo('/casino')
}, 4000, {
  leading: true,
  trailing: false,
})

// 体育维护
const sportsMaintainHandler = debounce(() => {
  console.log("🚸🚸🚸 ~ sportsMaintainHandler ~ 体育维护🔥🔥🔥",)
}, 4000, {
  leading: true,
  trailing: false,
})



function getDevice(url: string) {
  if (isPwa() && (url.includes('/member/reg') || url.includes('/member/login') || url.includes('/member/third/register')
    || url.includes('/deposit/bank/application') || url.includes('/third/deposit') || url.includes('/deposit/coin/application')))
    return 28
  // pwa中需要读取app的注册配置
  if (isPwa() && (url.includes('/member/brand/detail')))
    return 26
  const isMobile = window.innerWidth <= 768
  if (isMobile)
    return 25
  else return 24
}

/**
 * 不需要错误提示的接口
 */
const noNotifyArr = [
  '/game/original/mines',
  '/member/agency/config',
  '/member/agency/valid/member/count',
  '/member/agency/valid/member/detail',
  `/sport/${getSportsPlatId()}/place/bet`,
  '/member/promo/red/detail',
]

export const httpClient = new HttpClient({
  baseURL: PROD ? '' : '/api',
  timeout: VITE_HTTP_TIMEOUT,
  isEncryption: false,
  isSign: true,
  // showConsole: getEnv().MODE !== 'production',
  showConsole: false,
  postCborUrlList: [...cborUrlList],
  requestInterceptors: [
    // 设置token和dn
    async (config: any) => {
      const isAuth = config.method === 'get' ? config.params?.auth : config.data?.auth
      if (isAuth !== false) {
        if (isFlutterApp()) {
          const token = getFlutterAppToken()
          if (token)
            config.headers.t = token
        }
        else {
          const appStore = useAppStore()
          const token = appStore.getToken()
          if (token)
            config.headers.t = token
        }
      }

      return config
    },
    // 设置全局header
    (config: any) => {
      config.responseType = 'arraybuffer'
      config.headers.d = getDevice(config.url)
      config.headers.lang = getCurrentLanguageForBackend()
      config.headers.timets = new Date().getTime()
      config.headers['time-zone'] = timeZone.time_zone
      config.headers['x-id'] = window.performance.now()
      config.headers['x-ts'] = config.headers.timets
      const params = new URLSearchParams(document.location.search)
      const fbp = Cookie.get('_fbp')
      const fbc = Cookie.get('_fbc')
      if (fbp)
        config.headers.fbp = fbp

      if (fbc)
        config.headers.fbc = fbc

      const u = params.get('u')
      const c = params.get('c')
      if (c || u) {
        const val = c || u as string
        config.headers['x-c'] = val.replace(/\//g, '')
      }
      if (u !== null && u !== undefined)
        config.headers.u = u.replace(/\//g, '')
      if (c !== null && c !== undefined)
        config.headers.c = c.replace(/\//g, '')
      return config
    },
  ],
  responseInterceptors: [
    (response: any) => decompressZstd(response),
    // 处理ip或者地区限制
    // 如果响应header里面 ban = area 或者 ip，就跳转到限制页面
    (response: any) => {
      let ban = response.headers.ban
      if (ban === 'area' || ban === 'bl') {
        ban = ban === 'bl' ? 'ip' : 'area'
        window.limitType = ban
        console.log('response?.data?.data === ', response?.data?.data)
        const temp = { url: response.config.url, ban, data: response?.data?.data, response }
        return Promise.reject(temp)
      }
      return response
    },
    // 处理后端status为false的情况
    (response: any) => {
      const { status, data, tip } = response.data as IResponse<any>

      const responseStatus = response.status

      let tipMsg = ''
      if (tip && tip !== '0')
        tipMsg = tip

      if (!status) {
        if (isFlutterApp()) {
          sendMsgToFlutterApp(SendFlutterAppMessage.API_FALSE, JSON.stringify(response.data || {}))
          return
        }

        // 如果后端返回token，关闭所有请求，清除token
        if (data === 'token') {
          dataIsTokenHandler(responseStatus, response)
        }
        else if (data === 'maintain') {
          return sportsMaintainHandler()
        }
        else if (data === 'member-verify') {
          return Promise.reject(new Error(JSON.stringify(response.data)))
        }
        else {
          let requestData = {
            noNotify: false,
          }
          if (noNotifyArr.includes(response.config.url))
            requestData = response.config.data ? JSON.parse(response.config.data) : requestData

          if (!response.config.params?.noNotify && !requestData.noNotify && data !== '5024') {
            //TODO: 打印请求参数
            // openNotify({
            //   type: response.config.url.includes('/chat/send') ? 'chat' : 'error',
            //   code: `${responseStatus}`,
            //   title: tipMsg,
            //   // ${isTestEnv() ? `Url: ${response.config.url}<br />` : ''}
            //   message: `
            //     ${(getMsgByCode(data) ?? data) || t('sys_error')}
            //   `,
            // })
            message.error(getMsgByCode(data) ?? data)
          }
        }

        // 直接抛出错误，不再执行后续操作
        return Promise.reject(new Error(`{"url":"${response.config.url}发生错误","status":${status},"data":${JSON.stringify(data)}}`))
      }
      return response
    },
  ],
  responseErrorHandle: (error: any) => {
    const status = error.response.status
    if (status !== 403 && status !== 404 && !(`${status}`.startsWith('5'))) {
      // TODO:
      // openNotify({
      //   type: 'error',
      //   code: `${status}`,
      //   message: `
      //     ${isTestEnv() ? `Url: ${error.config.url}<br />` : ''}
      //     ${t('login_fail_tip')}
      //   `,
      // })
      // appEventBus.emit(EventBusNames.NEED_LOGiN_MSG)
    }
  },
})
